﻿// <copyright file="DEDalUtils.cs" company="The MITRE Corporation">
//    Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//    Licensed under the Apache License, Version 2.0 (the "License");
//    you may not use this file except in compliance with the License.
//    You may obtain a copy of the License at
//    http://www.apache.org/licenses/LICENSE-2.0
//    Unless required by applicable law or agreed to in writing, software
//    distributed under the License is distributed on an "AS IS" BASIS,
//    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//    See the License for the specific language governing permissions and
//    limitations under the License.
// </copyright>

/////////////////////////////////////////////////////////////////////////////////////////////////
// DEDalUtils.cs - Common Data Access Layer Utilities for EDXL-DE
// Project: IC.NET SOA - IC.NET DAL
//
// Language:    C#, .NET 4.0
// Platform:    Dell XPS m1530 Windows 7, VS 2010
// Author:      Don McGarry MITRE Rome
//              dmcgarry@mitre.org, (315) 838-2669
/////////////////////////////////////////////////////////////////////////////////////////////////

// Copyright (c) 2010 The MITRE Corporation. All rights reserved.
//
// NOTICE
// This software was produced for the U. S. Government
// under Contract No. FA8721-09-C-0001, and is
// subject to the Rights in Noncommercial Computer Software
// and Noncommercial Computer Software Documentation Clause
// (DFARS) 252.227-7014 (JUN 1995)

using System;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Linq;
using EDXLCoT;
using EDXLSharp;
using EDXLSharp.CAPLib;
using EDXLSharp.EDXLDELib;
using EDXLSharp.EDXLHAVE_2_0Lib;
using EDXLSharp.EDXLRMLib;
using ICNETServices;
using MEXLSitRepLib;
using MEXLTEPLib;

namespace ICNETDAL
{
  /// <summary>
  /// A collection of utilities for working with ICNET's Data Access Layer
  /// </summary>
  public static class DEDalUtils
  {
    #region Public Member Functions

    /// <summary>
    /// Turns a DE message into an a more specific type, such as a EDXLHAVE or CAP
    /// </summary>
    /// <param name="distributionElementObject">The DE object that will be unboxed</param>
    /// <returns>A list of the formatted objects</returns>
    public static List<IGeoRSS> UnboxContentObjectsForGeoRSS(EDXLDE distributionElementObject)
    {
      List<IGeoRSS> unboxedContentObjects = new List<IGeoRSS>();

      foreach (ContentObject contentObj in distributionElementObject.ContentObjects)
      {
        UnboxContentObjectForGeoRSS(contentObj, unboxedContentObjects);
      }

      foreach (ContentObject co in distributionElementObject.ContentObjects)
      {
        if (co.NonXMLContent != null)
        {
          unboxedContentObjects.Add(co.NonXMLContent);
        }
      }

      return unboxedContentObjects;
    }

    /// <summary>
    /// A helper method for unboxing content objects. 
    /// </summary>
    /// <param name="co">the content object that is being unboxed</param>
    /// <param name="unboxedContentObjects">The currently unboxed content objects</param>
    public static void UnboxContentObjectForGeoRSS(ContentObject co, List<IGeoRSS> unboxedContentObjects)
    {
      CAP capmsg;
      EDXLHAVE havemsg;
      SitRep sitRepmsg;
      TEP tepMessage;
      CoTWrapper cotmsg;
      ResourceMessageType resourceMessage;

      int index = -1;
      index = co.IndexOfNamedKeywordList(EDXLConstants.ContentKeywordListName);
      if (co.XMLContent != null && co.ContentKeyword != null && index != -1)
      {
        foreach (XElement doc in co.XMLContent.EmbeddedXMLContent)
        {
          if (co.ContentKeyword[index].Value.Contains("EDXL-CAP") || co.ContentKeyword[index].Value.Contains("CAP"))
          {
            capmsg = new CAP();
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            capmsg.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(capmsg);
          }
          else if (co.ContentKeyword[index].Value.Contains("EDXL-HAVE") || co.ContentKeyword[index].Value.Contains("HAVE"))
          {
            havemsg = new EDXLHAVE();
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            havemsg.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(havemsg);
          }
          else if (co.ContentKeyword[index].Value.Contains("EDXL-RM") || co.ContentKeyword[index].Value.Contains("EDXL-RM ResponseToRequestResource") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM ReportResourceDeploymentStatus") || co.ContentKeyword[index].Value.Contains("EDXL-RM ResponseToRequestExtendedDeploymentDuration") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM ResponseToRequestReturn") || co.ContentKeyword[index].Value.Contains("EDXL-RM OfferUnsolicitedResource") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM ReleaseResource") || co.ContentKeyword[index].Value.Contains("EDXL-RM ResponseToRequestResource") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM RequestQuote") || co.ContentKeyword[index].Value.Contains("EDXL-RM RequestResource") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM RequestReturn") || co.ContentKeyword[index].Value.Contains("EDXL-RM RequestExtendedDeploymentDuration") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM RequestInformation") || co.ContentKeyword[index].Value.Contains("EDXL-RM ResponseToRequestQuote") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM ResponseToRequestInformation") || co.ContentKeyword[index].Value.Contains("EDXL-RM CommitResource") ||
            co.ContentKeyword[index].Value.Contains("EDXL-RM RequestResourceDeploymentStatus"))
          {
            resourceMessage = new ResourceMessageType();
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            resourceMessage.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(resourceMessage);
          }
          else if (co.ContentKeyword[index].Value.Contains("EDXL-SitRep") ||
           co.ContentKeyword[index].Value.Contains("EDXL-SitRep CasualtyAndIllnessSummary") ||
           co.ContentKeyword[index].Value.Contains("EDXL-SitRep FieldObservation") ||
           co.ContentKeyword[index].Value.Contains("EDXL-SitRep ManagementReportingSummary") ||
           co.ContentKeyword[index].Value.Contains("EDXL-SitRep ResponseResourcesTotals") ||
           co.ContentKeyword[index].Value.Contains("EDXL-SitRep SituationInformation"))
          {
            // Normal XML
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            // Transform to XDocument (A type of XElement)
            XDocument document = new XDocument();
            using (XmlWriter xmlWriter = document.CreateWriter())
            {
              xdoc.WriteTo(xmlWriter);
            }

            EDXLSharp.EDXLSitRepLib.SitRep sitRepMsg = new EDXLSharp.EDXLSitRepLib.SitRep(document.Root);

            unboxedContentObjects.Add(sitRepMsg);
          }
          else if (co.ContentKeyword[index].Value.Contains("MEXL-SitRep") || co.ContentKeyword[index].Value.Contains("SitRep"))
          {
            sitRepmsg = new SitRep();
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            sitRepmsg.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(sitRepmsg);
          }
          else if (co.ContentKeyword[index].Value.Contains("MEXL-TEP") || co.ContentKeyword[index].Value.Contains("TEP"))
          {
            tepMessage = new TEP();
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            tepMessage.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(tepMessage);
          }
          else if (co.ContentKeyword[index].Value.Contains("CoTEvent"))
          {
            cotmsg = new CoTWrapper();
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            cotmsg.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(cotmsg);
          }
          else // handles all other xml types
          {
            OtherXMLWrapper xmlMsg = new OtherXMLWrapper(co.ContentKeyword[index].Value, co.ContentDescription);
            XmlDocument xdoc = new XmlDocument();
            using (XmlReader xr = doc.CreateReader())
            {
              xdoc.Load(xr);
            }

            xmlMsg.ReadXML(xdoc.FirstChild);
            unboxedContentObjects.Add(xmlMsg);
             
          }
          
        }
      }
    }

    /// <summary>
    /// Converts an XML object in the GML format to the GeoRSS format.
    /// </summary>
    /// <param name="xe">the XML element containg the GML data</param>
    /// <returns>an XML element containg the GeoRSS data</returns>
    public static XElement GmltoGeoRSSSimple(XElement xe)
    {
      XmlReader xr = xe.CreateReader();
      xr.Read();
      XNamespace georss = "http://www.georss.org/georss";
      XElement returnval = new XElement("gobble");
      string pointstr;
      switch (xr.Name)
      {
        case "Point":
          xr.Read();
          returnval = new XElement(georss + "point", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), xr.ReadElementContentAsString() });
          break;
        case "Polygon":
          xr.Read();
          xr.Read();
          xr.Read();
          pointstr = xr.ReadElementContentAsString();
          returnval = new XElement(georss + "polygon", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), pointstr });
          break;
        case "LineString":
          xr.Read();

          // xr.Read();
          pointstr = xr.ReadElementContentAsString();
          returnval = new XElement(georss + "line", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), pointstr });
          break;
        case "MultiGeometry":// Not Supported in Geo-RSS-Simple
          break;
        default:
          throw new ArgumentException("Unexpected Name: " + xr.Name + " in DEDalUtils.GmltoGeoRSSSimple");
      }

      // XmlWriter XWriter = returnval.CreateWriter();
      return returnval;
    }

    /// <summary>
    /// This function is depricated.
    /// </summary>
    /// <param name="xe">This parameter is not used. </param>
    /// <returns>This is not used.</returns>
    public static List<XElement> GmltoGeoRSSDepricated(XElement xe)
    {
      XmlReader xr = xe.CreateReader();
      xr.Read();
      XNamespace geo = ICNETSOAConstants.DepricatedGeoRSSNS;
      List<XElement> returnval = new List<XElement>();
      xr.Read();
      string value = xr.ReadElementContentAsString();
      char[] splitchar = new char[] { ' ' };
      string[] split = value.Split(splitchar);
      returnval.Add(new XElement(geo + "lat", new object[] { new XAttribute(XNamespace.Xmlns + "geo", ICNETSOAConstants.DepricatedGeoRSSNS), split[0] }));
      returnval.Add(new XElement(geo + "long", new object[] { new XAttribute(XNamespace.Xmlns + "geo", ICNETSOAConstants.DepricatedGeoRSSNS), split[1] }));
      return returnval;
    }

    /// <summary>
    /// Converts a circle in the GML format to the GeoRSS format.
    /// </summary>
    /// <param name="circleVal">The circle, in the GML format</param>
    /// <returns>A circle in GeoRSS</returns>
    public static XElement CircletoGeoRSSSimple(string circleVal)
    {
      XNamespace georss = "http://www.georss.org/georss";
      XElement returnval = new XElement("gobble");
      returnval = new XElement(georss + "circle", new object[] { new XAttribute(XNamespace.Xmlns + "georss", "http://www.georss.org/georss"), circleVal });
      return returnval;
    }
    
    /// <summary>
    /// Swaps a pair of latitude/longitude coordinates.
    /// </summary>
    /// <param name="latLon">The latitude/longitude coordinates, in the form "X, Y"</param>
    /// <param name="replaceComma">If true, it will replace the comma in the coordinates with a space</param>
    /// <returns>The swapped latitude/longitude.</returns>
    public static string SwapLatLon(string latLon, bool replaceComma)
    {
      int index;
      string lat, lon;
      index = latLon.IndexOf(",");
      lat = latLon.Substring(0, index);
      lon = latLon.Substring(index + 1);
      if (replaceComma)
      {
        return lon + " " + lat;
      }
      else
      {
        return lon + "," + lat;
      }
    }

    /// <summary>
    /// Deletes the ICNET database.
    /// </summary>
    public static void ClearCache()
    {
      EDXLSQLDataContext linqDB = new EDXLSQLDataContext(ICNETSOAConstants.ICNETConnectionString);
      linqDB.NukeDB();
    }

    #endregion
  }
}
